package com.itheima.dataSource;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DataSourceTest {
    //druid数据库连接池
    @Test
    public void test1() throws SQLException {
        //创建druid数据库连接池对象
        DruidDataSource dataSource = new DruidDataSource();
        //设置数据库连接的四大基本特征,连接数据库
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://39.101.203.144:3306/db_HZC");
        dataSource.setUsername("root");
        dataSource.setPassword("root");

        //获取连接
        Connection connection = dataSource.getConnection();
    }


    //通过spring配置的方式获取druid数据库连接池
    @Test
    public void test2() throws SQLException {
        //通过spring配置文件创建ioc容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        //从IOC容器中获取数据库连接池对象
        DataSource dataSource = ctx.getBean("dataSource", DataSource.class);
        //获取连接对象
        Connection connection = dataSource.getConnection();
        System.out.println("connection = " + connection);
    }




//    c3p0数据库连接池
    @Test
    public void test3() throws SQLException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        DataSource dataSource1 = context.getBean("dataSource1", DataSource.class);

        //获取连接
        Connection connection = dataSource1.getConnection();

        System.out.println("connection = " + connection);
    }
}
